<template>
  <basic-container>
    <el-tabs class="attach-tabs" style="margin: 0 10px" v-model="activeName" @tab-click="handleTabClick">
      <el-tab-pane label="ESOP文件" name="esop"> </el-tab-pane>
      <el-tab-pane label="品质检验模板" name="qms"></el-tab-pane>
      <el-tab-pane label="APP上传" name="app"></el-tab-pane>
      <el-tab-pane label="其他文件" name="other"></el-tab-pane>
    </el-tabs>
    <avue-crud
      :option="option"
      :table-loading="loading"
      :data="data"
      :page.sync="page"
      :search.sync="query"
      :permission="permissionList"
      :before-open="beforeOpen"
      v-model="form"
      ref="crud"
      :key="timer"
      @row-del="rowDel"
      @search-change="searchChange"
      @search-reset="searchReset"
      @selection-change="selectionChange"
      @current-change="currentChange"
      @size-change="sizeChange"
      @refresh-change="refreshChange"
      @on-load="onLoad"
    >
      <template slot="menuLeft">
        <el-button type="primary" size="small" plain v-if="permission.attach_upload && activeName !== 'app'" icon="el-icon-upload2" @click="handleUpload">上 传</el-button>
        <el-button type="danger" size="small" icon="el-icon-delete" plain v-if="permission.attach_delete" @click="handleDelete">删 除</el-button>
      </template>
      <template slot-scope="scope" slot="menu">
        <el-button type="text" icon="el-icon-view" size="small" v-if="permission.attach_preview" @click="preview(scope.row)">预览</el-button>
        <el-button type="text" icon="el-icon-download" size="small" v-if="permission.attach_download" @click="handleDownload(scope.row)">下载</el-button>
      </template>
      <template slot-scope="{ row }" slot="attachSize">
        <el-tag>{{ `${row.attachSize} KB` }}</el-tag>
      </template>
    </avue-crud>
    <el-dialog title="附件管理" append-to-body :visible.sync="attachBox" width="555px">
      <avue-form v-if="attachBox" ref="form" :option="attachOption" v-model="attachForm" :upload-before="uploadBefore" :upload-after="uploadAfter">
        <template slot="attachFile">
          <el-upload
            ref="upload"
            class="upload-demo"
            drag
            action="/api/blade-resource/oss/endpoint/put-file-attach"
            :data="attachForm"
            :headers="headersObj"
            :auto-upload="false"
            :show-file-list="false"
            :on-change="handleChange"
          >
            <i class="el-icon-upload"></i>
            <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
          </el-upload>
        </template>
      </avue-form>
    </el-dialog>
    <el-dialog
      ref="dialog"
      title="查看ESOP"
      append-to-body
      :visible.sync="showEsopDialog"
      :full-screen="fullScreen"
      :class="[fullScreen ? 'fullscreen' : 'no_fullScreen']"
      :close-on-click-modal="false"
      @close="fullScreen = false"
    >
      <iframe ref="pdf" :src="pdfUrl" width="100%" :height="iframeHeight"></iframe>
      <div slot="title" class="dialog-title">
        <span class="title">查看ESOP</span>
        <span class="el-dialog__close fullscreen-icon" @click="handleFullScreen">
          <i class="el-icon-full-screen"></i>
        </span>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button size="small" @click="showEsopDialog = false"><i class="el-icon-circle-close"></i><span>取 消</span></el-button>
      </span>
    </el-dialog>
    <!-- <common-modal-template ref="commonModalTemplate" :option="tableOption" @getSelectedRows="getSelectedRows" :key="timer" @newKey="newKey"></common-modal-template> -->
    <doc-preview :url="fileUrl" :visiable.sync="previewVisible" :file-type="fileType"></doc-preview>
  </basic-container>
</template>

<script>
import CommonModalTemplate from '@/components/common-modal-template/common-modal-template.vue';
import { option, getTableOption, attachOption, getAttachOption } from '@/views/resource/attach';
import { getList, getDetail, remove, existFile } from '@/api/resource/attach';
import { mapGetters } from 'vuex';
import { downLoad } from '@/api/resource/attach';
import DocPreview from '@/components/filePreview/docPreview';
import website from '@/config/website';
import { Base64 } from 'js-base64';
import { getToken } from '@/util/auth';
export default {
  name: 'ResourceAttach',
  components: {
    CommonModalTemplate,
    DocPreview
  },
  mixins: [],
  data() {
    return {
      isUpload: false,
      file: null,
      pageCode: 'ATTACH',
      fullScreen: false,
      form: {},
      loading: true,
      tableOption: {},
      page: {
        pageSize: 20,
        currentPage: 1,
        total: 0
      },
      previewVisible: false,
      fileType: '',
      fileUrl: '',
      tabsObj: {
        esop: 'ESOP',
        qms: 'QMS',
        app: 'APP'
      },
      tabsObjName: {
        esop: 'ESOP文件',
        qms: '品质检验模板',
        app: 'APP上传',
        other: '其他文件'
      },
      query: {
        attachType: 'ESOP'
      },
      timer: new Date().getTime(),
      attachBox: false,
      selectionList: [],
      activeName: 'esop',
      option,
      data: [],
      attachForm: {},
      attachOption: attachOption(this),
      showEsopDialog: false,
      pdfUrl: ''
    };
  },
  mounted() {
    this.$nextTick(() => {
      this.structuralSplit();
    });
  },
  computed: {
    ...mapGetters(['permission']),
    permissionList() {
      return {
        addBtn: false,
        editBtn: false,
        viewBtn: false,
        delBtn: this.vaildData(this.permission.attach_delete, false)
      };
    },
    ids() {
      let ids = [];
      this.selectionList.forEach((ele) => {
        ids.push(ele.id);
      });
      return ids.join(',');
    },
    iframeHeight() {
      const docHeight = document.documentElement.clientHeight;
      const iframeHeight = docHeight - 188 + 'px';
      return this.fullScreen ? iframeHeight : '600px';
    },
    headersObj() {
      let header = { Authorization: `Basic ${Base64.encode(`${website.clientId}:${website.clientSecret}`)}` };
      header['Blade-Auth'] = 'bearer ' + getToken();
      return header;
    }
  },
  methods: {
    structuralSplit() {
      if ($('.informationLabel').length === 0) {
        let card = $('#app .el-card .is-never-shadow');
        let searchSon = $(card[0]).find('.avue-form');
        let searchFather = document.createElement('div');
        searchFather.className = 'informationLabel el-tabs el-tabs--top el-tabs--border-card';
        searchFather.innerHTML = `<div class="el-tabs__header is-top">
              <div class="el-tabs__nav-wrap is-top">
                <div class="el-tabs__nav-scroll">
                  <div role="tablist" class="el-tabs__nav is-top" style="transform: translateX(0px);">
                    <div id="tab-0" aria-controls="pane-0" role="tab" aria-selected="true" tabindex="0" class="el-tabs__item is-top is-active">
                      ${this.tabsObjName[this.activeName]}搜索
                    </div>
                  </div>
                </div>
              </div>
              <div class="el-tabs__content" style="padding: 10px 10px 0 10px;background-color: #ffffff;"></div>
            </div>`;
        $(searchFather).find('.el-tabs__content').append(searchSon);
        $('#app .avue-crud__search .el-card__body').append(searchFather);

        let inputs = $('.avue-crud__search .avue-form__group .avue-form__row');
        if (inputs.length > 0) {
          let elForm = $(inputs[0]).find('.el-form-item__content');
          let elInput = $(inputs[0]).find('.el-input');
          if (this.activeName !== 'other') {
            $(elInput).attr('class', 'el-input el-input--small is-disabled el-input--suffix');
            elForm.append('<div class="custom-disabled"></div>');
          } else {
            $(elInput).attr('class', 'el-input');
          }
        }
      }
    },
    handleTabClick() {
      this.newKey();
      this.page = {
        pageSize: 20,
        currentPage: 1,
        total: 0
      };
      this.query = {};
      this.query.attachType = this.tabsObj[this.activeName];
      const colum = getTableOption(this.activeName, this);
      const attachColum = getAttachOption(this.activeName, this);
      this.$set(this.option, 'column', colum);
      this.$set(this.attachOption, 'column', attachColum);
      this.onLoad(this.page, this.query);
      this.this.$refs.crud.refreshTable();
      this.$refs.form.resetForm();
    },
    handleUpload() {
      this.attachBox = true;
      this.$nextTick(() => {
        this.isUpload = false;
        this.file = null;
        this.$refs.form.resetFields();
        this.$refs.upload.clearFiles();
      });
      this.attachForm = {};
    },
    uploadBefore(res, done, loading, column) {
      if (!this.attachForm.attachType) {
        this.$message({
          type: 'warning',
          message: '请选择附件类型!'
        });
        loading();
      } else {
        done();
      }
    },
    uploadAfter(res, done, loading, column) {
      this.attachBox = false;
      this.refreshChange();
      done();
    },
    handleChange(file, files) {
      if (!this.attachForm.attachType) {
        this.$message({
          type: 'warning',
          message: '请选择附件类型!'
        });
        this.file = null;
        this.$refs.upload.clearFiles();
        return;
      }
      if (!this.isUpload) {
        this.file = file;
        let formData = new FormData();
        formData.append('file', file.raw);
        formData.append('attachType', this.attachForm.attachType);
        existFile(formData)
          .then((res) => {
            if (res.data.code === 200) {
              let data = res.data.data;
              if (data) {
                this.$confirm('已有相同名称文件，是否替换?', {
                  confirmButtonText: '确定',
                  cancelButtonText: '取消',
                  type: 'warning'
                })
                  .then(() => {
                    this.isUpload = true;
                    this.$refs.upload.submit();

                    setTimeout(() => {
                      this.file = null;
                      this.$refs.upload.clearFiles();
                      this.attachBox = false;
                      this.refreshChange();
                    }, 200);
                  })
                  .catch(() => {});
              } else {
                this.isUpload = true;
                this.$refs.upload.submit();
                setTimeout(() => {
                  this.file = null;
                  this.$refs.upload.clearFiles();
                  this.attachBox = false;
                  this.refreshChange();
                }, 200);
              }
            }
          })
          .catch(() => {
            this.file = null;
            this.$refs.upload.clearFiles();
          });
      }
    },
    handleDownload(row) {
      window.open(`${row.link}`);
    },
    rowDel(row) {
      this.$confirm('确定将选择数据删除?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          return remove(row.id);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: 'success',
            message: '操作成功!'
          });
        });
    },
    handleDelete() {
      if (this.selectionList.length === 0) {
        this.$message.warning('请选择至少一条数据');
        return;
      }
      this.$confirm('确定将选择数据删除?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          return remove(this.ids);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: 'success',
            message: '操作成功!'
          });
          this.$refs.crud.toggleSelection();
        });
    },
    beforeOpen(done, type) {
      if (['edit', 'view'].includes(type)) {
        getDetail(this.form.id).then((res) => {
          this.form = res.data.data;
        });
      }
      done();
    },
    searchReset() {
      this.query = {};
      this.onLoad(this.page);
    },
    searchChange(params, done) {
      this.query = params;
      this.page.currentPage = 1;
      this.onLoad(this.page, params);
      done();
    },
    selectionChange(list) {
      this.selectionList = list;
    },
    selectionClear() {
      this.selectionList = [];
      this.$refs.crud.toggleSelection();
    },
    currentChange(currentPage) {
      this.page.currentPage = currentPage;
    },
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
    },
    refreshChange() {
      this.onLoad(this.page, this.query);
    },
    onLoad(page, params = {}) {
      this.$nextTick(() => {
        this.structuralSplit();
      });
      if (this.activeName === 'other') {
        if (!this.query.attachType) {
          params.attachTypeStr = 'EXCEL,PERSONNEL';
        } else {
          params.attachTypeStr = this.query.attachType;
        }
        delete this.query.attachType;
        delete params.attachType;
      }
      this.loading = true;
      getList(page.currentPage, page.pageSize, Object.assign(params, this.query)).then((res) => {
        const data = res.data.data;
        this.page.total = data.total;
        this.data = data.records;
        this.loading = false;

        this.selectionClear();
      });
    },
    preview(row) {
      const fileType = this.getFileType(row.link);
      if (['doc', 'docx', 'xlsx', 'xls'].includes(fileType)) {
        this.previewVisible = true;
        this.fileUrl = row.link;
        this.fileType = fileType;
        return;
      }
      if (row.link.indexOf('pdf') != -1) {
        downLoad({ link: row.link }).then(
          (res) => {
            let fileURL = null;
            var blob = new Blob([res.data], { type: 'application/pdf' });
            if (window.createObjectURL != undefined) {
              // basic
              fileURL = window.createObjectURL(blob);
            } else if (window.webkitURL != undefined) {
              // webkit or chrome
              try {
                fileURL = window.webkitURL.createObjectURL(blob);
              } catch (error) {
                console.log(error);
              }
            } else if (window.URL != undefined) {
              // mozilla(firefox)
              try {
                fileURL = window.URL.createObjectURL(blob);
              } catch (error) {
                console.log(error);
              }
            }
            this.pdfUrl = '/pdf/web/viewer.html?file=' + encodeURIComponent(fileURL);
            this.showEsopDialog = true;
          },
          (error) => {}
        );
      } else {
        this.$ImagePreview([{ url: row.link }], 0, {
          closeOnClickModal: false
        });
      }
    },
    getFileType(url) {
      // 从URL中提取文件名
      const filename = url.split('/').pop();
      // 提取文件名的扩展名
      const fileExtension = filename.split('.').pop();
      return fileExtension;
    },
    handleFullScreen() {
      this.fullScreen = !this.fullScreen;
    },
    getSelectedRows(rowData) {
      this.query.partNo = rowData.partNo;
    },
    /**
     * 重新加载公用表格弹窗组件
     */
    newKey() {
      this.timer = new Date().getTime();
    },
    /**
     * 打开选择物料模态框
     */
    openPartCommonModal() {
      this.modalName = 'partModal';
      this.$refs.commonModalTemplate.showModal();
      this.tableOption = {
        modalTitle: '选择物料编码（双击进行选择）',
        url: '/api/mes-admin/part-master/page?semifinished=false',
        isPage: true,
        rowSelectionType: 'single',
        columnDefs: [
          {
            label: '物料编码',
            prop: 'partNo',
            search: true
          },
          {
            label: '物料名称',
            prop: 'name',
            search: true
          },
          {
            label: '物料型号',
            prop: 'partModel'
          }
        ]
      };
    }
  }
};
</script>

<style scoped lang="scss" scoped>
::v-deep .avue-crud .custom-disabled {
  position: absolute;
  width: 100%;
  height: 100%;
  top: 0;
  right: 0;
  opacity: 0;
  cursor: not-allowed;
}

::v-deep .el-tabs--border-card {
  border: none;
}
::v-deep .el-card__body {
  padding: 0;
}
::v-deep .el-tabs__content {
  padding: 0;
}

.dialog-title {
  position: relative;
  .title {
    display: inline-block;
  }
  .fullscreen-icon {
    position: absolute;
    right: 20px;
    cursor: pointer;
    display: inline-block;
    font-size: 14px;
    color: #909399;
    &:hover {
      color: #0a84ff;
    }
  }
}

.fullscreen {
  ::v-deep .el-dialog {
    width: 100%;
    margin: 0 !important;
    margin-top: 0vh !important;
  }
}
.no_fullScreen {
  ::v-deep.el-dialog {
    width: 50%;
    margin-top: 5vh !important;
  }
}
.attach-tabs {
  ::v-deep .el-tabs__header {
    border-bottom: none;
  }
  ::v-deep .el-tabs__content {
    display: none;
  }
}
</style>
